/*
 * Connection.cpp
 *
 *  Created on: 03/06/2011
 *      Author: dela
 */

#include "Connection.h"

using namespace std;

/**
 *
 */
int Connection::initConnection() {
	return socket.connectSocket( ip, port );
}


/**
 *
 */
bool Connection::login( std::string user, std::string password ) {
	//Tipo de operación:
	char op = 1;
	socket.sendData(1, &op);

	//Nombre:
	socket.sendData(user.size(), user.c_str());

	//Password:
	socket.sendData(password.size(), password.c_str());

	//Recibo resultado:
	char *data;
	socket.receiveData(&data);
	bool returnValue = (bool) *data;
	delete[] data;
	return returnValue;
}

/**
 *
 */
bool Connection::createCourse(Course &c) {
	//Tipo de operación:
	char op = 2;
	socket.sendData(1, &op);

	//Obtengo buff:
	int size;
	char *buff = c.toBuffer( &size );
	socket.sendData(size, buff);

	//Recibo resultado:
	char *data;
	socket.receiveData(&data);
	bool returnValue = (bool) *data;
	delete[] data;
	delete[] buff;
	return returnValue;
}

/**
 *
 */
void Connection::getCourses(list<Course> &courses) {
	//Tipo de operación:
	char op = 3;
	socket.sendData(1, &op);

	//Recibo cantidad:
	int amount = 0;
	char *data;
	socket.receiveData(&data);
	amount = (int) *data;
	delete[] data;

	//Recibo:
	for (int i=0; i<amount; i++ ) {
		socket.receiveData(&data);
		Course c(data);
		courses.insert(courses.end(), c);
		delete[] data;
	}
}


/**
 *
 */
void Connection::getClasses(list<Class> &classes) {
	//Tipo de operación:
	char op = 5;
	socket.sendData(1, &op);

	//Recibo cantidad:
	int amount = 0;
	char *data;
	socket.receiveData(&data);
	amount = (int) *data;
	delete[] data;

	//Recibo:
	for (int i=0; i<amount; i++ ) {
		socket.receiveData(&data);
		Class c(data);
		classes.insert(classes.end(), c);
		delete[] data;
	}
}



/**
 *
 */
bool Connection::createClass(Class &c) {
	//Tipo de operación:
	char op = 4;
	socket.sendData(1, &op);

	//Obtengo buff:
	int size;
	char *buff = c.toBuffer( &size );
	socket.sendData(size, buff);

	//Recibo resultado:
	char *data;
	socket.receiveData(&data);
	bool returnValue = (bool) *data;
	delete[] data;
	delete[] buff;
	return returnValue;
}
